package com.knife.blog.web.action;

import java.io.File;

import org.apache.commons.fileupload.FileItem;

import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.BlogUser;
import com.knife.blog.logic.BlogNewsDocService;
import com.knife.blog.logic.BlogUserService;
import com.knife.blog.logic.impl.BlogCoreServiceImpl;
import com.knife.blog.logic.impl.BlogUserServiceImpl;
import com.knife.util.CommUtil;
import com.knife.util.FileUtil;
import com.knife.util.MD5;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.web.tools.ActiveUser;
import com.knife.web.tools.IActiveUser;
import com.knife.web.tools.IPageList;

public class BlogUserAction extends BaseCmdAction {

    private BlogNewsDocService blogDocService = BlogCoreServiceImpl.getInstance();
    private BlogUserService blogUserService = BlogUserServiceImpl.getInstance();

    public Page doInit(WebForm form, Module module) {
        return module.findPage("login");
    }

    public Page doEdit(WebForm form, Module module) {
        String cid = (String) form.get("cid");
        BlogUser bloguser = blogUserService.getBlogUser("cid", cid);
        form.addPo(bloguser);
        return module.findPage("edit");
    }

    public Page doEditU(WebForm form, Module module) {
        String cid = (String) form.get("cid");
        BlogUser bloguser = blogUserService.getBlogUser("cid", cid);
        form.addPo(bloguser);
        return module.findPage("editu");
    }

    public Page doAdd(WebForm form, Module module) {
        BlogUser buser = (BlogUser) form2Obj(form);
        boolean ret = blogUserService.add(buser);
        if (ret) {
            form.addResult("msg", "添加成功!");
            return this.doList(form, module);
        } else {
            form.addResult("msg", "添加失败!");
            return module.findPage("edit");
        }
    }

    public Page doDel(WebForm form, Module module) {
        boolean ret = blogUserService.delBlogInfo((String) form.get("cid"));
        form.addResult("msg", ret ? "删除成功!" : "删除失败!");
        return this.doList(form, module);
    }

    public Page doDelU(WebForm form, Module module) {
        boolean ret = blogUserService.delBlogInfo((String) form.get("cid"));
        form.addResult("msg", ret ? "删除成功!" : "删除失败!");
        return this.doListu(form, module);
    }

    public Page doDelBatch(WebForm form, Module module) {
        String ids[] = ((String) form.get("mulitCid")).split(",");
        boolean ret = false;
        for (int i = 0; i < ids.length; i++) {
            ret = blogUserService.delBlogInfo(ids[i]);
        }
        form.addResult("msg", ret ? "删除成功!" : "删除失败!");
        return this.doList(form, module);
    }

    public Page doDelBatchU(WebForm form, Module module) {
        String ids[] = ((String) form.get("mulitCid")).split(",");
        boolean ret = false;
        for (int i = 0; i < ids.length; i++) {
            ret = blogUserService.delBlogInfo(ids[i]);
        }
        form.addResult("msg", ret ? "删除成功!" : "删除失败!");
        return this.doListu(form, module);
    }

    public Page doCheck(WebForm form, Module module) {
        boolean ret = blogUserService.check((String) form.get("cid"));
        form.addResult("msg", ret ? "审核成功!" : "审核失败!");
        return this.doListu(form, module);
    }

    public Page doCheckBatch(WebForm form, Module module) {
        String ids[] = ((String) form.get("mulitCid")).split(",");
        boolean ret = false;
        for (int i = 0; i < ids.length; i++) {
            ret = blogUserService.check(ids[i]);
        }
        form.addResult("msg", ret ? "审核成功!" : "审核失败!");
        return this.doListu(form, module);
    }

    public Page doUnCheck(WebForm form, Module module) {
        boolean ret = blogUserService.unCheck((String) form.get("cid"));
        form.addResult("msg", ret ? "取消成功!" : "取消失败!");
        return this.doList(form, module);
    }

    public Page doUnCheckBatch(WebForm form, Module module) {
        String ids[] = ((String) form.get("mulitCid")).split(",");
        boolean ret = false;
        for (int i = 0; i < ids.length; i++) {
            ret = blogUserService.unCheck(ids[i]);
        }
        form.addResult("msg", ret ? "取消成功!" : "取消失败!");
        return this.doList(form, module);
    }

    public Page doUpdate(WebForm form, Module module) {
        boolean ret = blogUserService.updateUserInfo((BlogUser) form2User(form));
        form.addResult("msg", ret ? "修改成功!" : "修改失败!");
        return this.doList(form, module);
    }

    public Page doUpdateU(WebForm form, Module module) {
        boolean ret = blogUserService.updateUserInfo((BlogUser) form2User(form));
        form.addResult("msg", ret ? "修改成功!" : "修改失败!");
        return this.doListu(form, module);
    }

    public Page doManageSetElite(WebForm form, Module module) {
        String cid = (String) form.get("cid");
        int updatetype = Integer.parseInt(form.get("updatetype").toString());
        int updatevalue = Integer.parseInt(form.get("updatevalue").toString());
        boolean ret = false;
        switch (updatetype) {
            case 1:
                ret = blogUserService.setBlogInfoNew(cid, updatevalue);
                break;
            case 2:
                ret = blogUserService.setBlogInfoElite(cid, updatevalue);
                break;
            case 3:
                ret = blogUserService.setBlogInfoHot(cid, updatevalue);
                break;
            default:
                ret = false;
                break;
        }
        //boolean ret=blogUserService.setBlogInfoElite(cid,updatevalue);
        //boolean ret=blogUserService.updateUserInfo((BlogUser)form2User(form));
        form.addResult("msg", ret ? "修改成功!" : "修改失败!");
        return this.doList(form, module);
    }

    public Page doList(WebForm form, Module module) {
        int currentPage = CommUtil.null2Int(form.get("page"));
        if (currentPage < 1) {
            currentPage = 1;
        }
        int pageSize = 10;
        try {
            IPageList pList = blogUserService.queryUserInfo("inputtime", currentPage, pageSize, 1);
            form.addResult("list", pList.getResult());
            form.addResult("pages", new Integer(pList.getPages()));
            form.addResult("rows", new Integer(pList.getRowCount()));
            form.addResult("page", new Integer(pList.getCurrentPage()));
            form.addResult("gotoPageHTML", CommUtil.showPageHtml(pList.getCurrentPage(), pList.getPages()));
        } catch (Exception e) {
            System.out.println("获取博客列表信息时出现了异常：");
            e.printStackTrace();
        }
        return module.findPage("list");
    }

    public Page doListu(WebForm form, Module module) {
        int currentPage = CommUtil.null2Int(form.get("page"));
        if (currentPage < 1) {
            currentPage = 1;
        }
        int pageSize = 10;
        try {
            IPageList pList = blogUserService.queryUserInfo("inputtime", currentPage, pageSize, 0);
            form.addResult("list", pList.getResult());
            form.addResult("pages", new Integer(pList.getPages()));
            form.addResult("rows", new Integer(pList.getRowCount()));
            form.addResult("page", new Integer(pList.getCurrentPage()));
            form.addResult("gotoPageHTML", CommUtil.showPageHtml(pList.getCurrentPage(), pList.getPages()));
        } catch (Exception e) {
            System.out.println("获取博客列表信息时出现了异常：");
            e.printStackTrace();
        }
        return module.findPage("listu");
    }
    
    public Page doRegBlog(WebForm form, Module module) {
        if (user == null) {
            // 请先登录
            form.addResult("url", "blogUser.do?parameter=register");
            form.addResult("msg", "请先登录！");
            return module.findPage("login");
            //return module.findPage("userReg");
        }
        form.addResult("username", user.getUserName());
        //System.out.println("BlogUserAction.username"+user.getUserName());
        BlogInfo blog = userService.getUserBlog(user.getUserName());
        if (blog != null) {
            return doSetting(form, module);
        }
        return module.findPage("register");
    }
    
    public Page doSetting(WebForm form, Module module) {
        BlogInfo myblog = userService.getUserBlog(user.getUserName());
        form.addResult("blog", myblog);
        form.addPo(myblog);
        return module.findPage("setting");
    }
    
    public Page doSaveSetting(WebForm form, Module module) {
        BlogInfo blogInfo = (BlogInfo) form2Obj(form);
        //上传图片到服务器
        try {
            FileItem file = (FileItem) form.get("file");
            if (!file.getName().equals("")) {
                String upurl = uploadFile(file);
                if (!upurl.equals("")) {
                    blogInfo.setTagimg(upurl);
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
        }
        boolean ret = userService.settingBlogInfo(blogInfo);

        form.addResult("msg", ret ? "设置成功!" : "设置失败!");
        return doSetting(form, module);
    }
    
    public String uploadFile(FileItem file) {
        String clientName = file.getName();
        FileUtil.isImgageFile(clientName);
        String retv_url = "";
        if (file != null) {
            String filePath = Globals.APP_BASE_DIR + "upfile/blog/headpic"
                    + "/";
            File fdir = new File(filePath);
            if (!fdir.exists()) {
                fdir.mkdirs();
            }
            try {
                String fileName = (clientName.substring(clientName.lastIndexOf(File.separator) + 1)).split("\\.")[1];
                fileName = CommUtil.getRandString(8) + "." + fileName;
                file.write(new File(filePath + fileName));
                retv_url = "/upfile/blog/headpic/" + fileName;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return retv_url;
    }

    public Page doSettingP(WebForm form, Module module) {
        BlogUser blogUser = userService.getBlogUser(user.getUserName());
        BlogInfo myblog = userService.getUserBlog(user.getUserName());
        form.addResult("blog", myblog);
        form.addPo(blogUser);
        return module.findPage("settingp");
    }

    public Page doSettingUserP(WebForm form, Module module) {
        BlogUser blogUser = userService.getBlogUser(user.getUserName());
        BlogInfo myblog = userService.getUserBlog(user.getUserName());
        form.addResult("blog", myblog);
        form.addPo(blogUser);
        return module.findPage("settingp");
    }

    public Page doSaveSettingP(WebForm form, Module module) {
        boolean ret = userService.updateUserInfo((BlogUser) form2User(form));
        form.addResult("msg", ret ? "设置成功!" : "设置失败!");
        return doSettingP(form, module);
    }

    public Page doShowChangePassword(WebForm form, Module module) {
        return module.findPage("changePassword");
    }

    public Page doShowChangeUserPassword(WebForm form, Module module) {
        BlogInfo myblog = userService.getUserBlog(user.getUserName());
        form.addResult("blog", myblog);
        return module.findPage("userPassword");
    }

    public Page doChangePassword(WebForm form, Module module) {
        String oldPassword = CommUtil.null2String(form.get("oldPassword"));
        String password = CommUtil.null2String(form.get("password"));
        String password1 = CommUtil.null2String(form.get("password1"));
        if (!MD5.encode(oldPassword).equals(
                ((ActiveUser) this.getCurrentUser(form)).getPassword())) {
            form.addResult("msg", "旧密码不正确，不能修改密码!");
            return module.findPage("changePassword");
        }
        if (!password.equals(password1)) {
            form.addResult("msg", "两次输入的密码不正确!");
            return module.findPage("changePassword");
        }
        //user.setPassword(MD5.encode(CommUtil.null2String(form.get("password"))));
        if (userService.changePassword(this.getCurrentUser(form).getUserName(),
                oldPassword, password)) {
            form.addResult("msg", "密码修改成功，下次登录时生效!");
            return new Page("clientforward", "/tools/forward.html", "template");
        } else {
            form.addResult("msg", "密码修改失败!");
            return module.findPage("changePassword");
        }
    }
    
    public Page doResetPassword(WebForm form, Module module) {
    	String cid = CommUtil.null2String(form.get("cid"));
    	//BlogUser buser = (BlogUser) form2User(form);
    	BlogUser buser = blogUserService.getBlogUser("cid", cid);
    	buser.setPassword(MD5.encode("123456"));
    	boolean ret=userService.updateUserInfo(buser);
    	//boolean ret=userService.changePassword(buser.getUsername(),buser.getPassword(), "123456");
        form.addResult("msg", ret ? "修改成功!" : "修改失败!");
        return this.doList(form, module);
    }

    public Page doShowChoiceTemplate(WebForm form, Module module) {
        return module.findPage("choiceTemplate");
    }

    public Page doChangeTemplate(WebForm form, Module module) {
        IActiveUser user = this.getCurrentUser(form);
        BlogInfo myblog = userService.getUserBlog(user.getUserName());
        myblog.setTemplate((String) form.get("template"));
        userService.blogInfoChange(myblog);
        com.knife.blog.logic.HTMLGenerater.saveCSS(myblog);
        myblog.setUpdated(Boolean.TRUE);
        form.addResult("url", "/blogTemplate.do");
        return new Page("clientforward", "/tools/forward.html", "template");
    }

    public Page doCreateTemplate(WebForm form, Module module) {
        return null;
    }

    public Page doVisitCount(WebForm form, Module module) {
        String cid = CommUtil.null2String(form.get("cid"));
        BlogInfo blog = userService.getBlogInfo(cid);
        blog.setReadtimes(new Integer(blog.getReadtimes() != null ? blog.getReadtimes().intValue() + 1 : 1));
        userService.updateVisitCount(blog);
        return null;
    }

    public Page doDocVisitCount(WebForm form, Module module) {
        String cid = CommUtil.null2String(form.get("cid"));
        blogDocService.readBlogNewsDoc(cid);
        return null;
    }

    public Object form2Obj(WebForm form) {
        String cid = CommUtil.null2String(form.get("cid"));
        BlogInfo obj = userService.getBlogInfo(cid);
        if (obj == null) {
            obj = new BlogInfo();
        }
        // 此处需要修改，妨止系统字段被从外面非法赋值
        form.toPo(obj);
        return obj;
    }

    public Object form2User(WebForm form) {
        String cid = CommUtil.null2String(form.get("cid"));
        BlogUser obj = userService.getBlogUser("cid", cid);
        if (obj == null) {
            obj = new BlogUser();
        }
        // 此处需要修改，妨止系统字段被从外面非法赋值
        form.toPo(obj);
        return obj;
    }

    public Page doGenerateBlog(WebForm form, Module module){
        boolean ret = blogUserService.generateBlog((String) form.get("cid"));
        form.addResult("msg", ret ? "生成成功!" : "生成失败!");
        return this.doList(form, module);
    }

    public Page doGenerateBlogBatch(WebForm form, Module module) {
        String ids[] = ((String) form.get("mulitCid")).split(",");
        boolean ret = false;
        for (int i = 0; i < ids.length; i++) {
            ret = blogUserService.generateBlog(ids[i]);
        }
        form.addResult("msg", ret ? "生成成功!" : "生成失败!");
        return this.doList(form, module);
    }
}